from rest_framework import viewsets, permissions
from rest_framework.decorators import action
from rest_framework.response import Response
from task.models import Task
from teacher.serializer import TeacherSerializer
from djangoStudy.db import DBUtils
from django.db.models import Q, F
from djangoStudy.tool import teacher_build_query

class TeacherViewSet(viewsets.ModelViewSet):
    queryset = Task.objects.all()
    serializer_class = TeacherSerializer
    permission_classes = (permissions.AllowAny,)
    """
    
    所有教师端任务 接口都在这里开发， 接口定义如下， 其中 TeacherSearch为路由名，
     
    是http://localhost:8000/teacher/TeacherSearch/
    
    不用动urls中的东西
    
    例子：
    @action(detail=False, methods=['POST'])
    def TeacherSearch(self, request):
        pass  #里面写 序列化或者sql语句
    """
    @action(detail=False, methods=['POST'])
    def teacherQuery(self, request, *args, **kwargs):
        """拿到教师端所有任务"""
        data = request.data
        base_sql = """
            SELECT 
                    t.id as id,
                    t.title AS title,
                    t.detail AS detail,
                    t.completed AS completed,
                    l.name AS l_name,
                    m.name AS m_name
            FROM 
                    tb_task t
            inner JOIN 
                    tb_language l ON t.language_id = l.id
            inner JOIN 
                    tb_module m ON t.module_id = m.id 
        """
        # 构建查询
        data_sql, data_params = teacher_build_query(base_sql, data)

        total_sql = """
            SELECT 
                    count(*)
                FROM 
                    tb_task t
                inner JOIN 
                    tb_language l ON t.language_id = l.id
                inner JOIN 
                    tb_module m ON t.module_id = m.id 
        """
        total_sql, total_params = teacher_build_query(total_sql, data, True)

        total = DBUtils.select_all(total_sql,total_params)
        result = DBUtils.select_all(data_sql, data_params)

        total_num = total[0]['count(*)'] if total else 0
        return Response(data={'data': result, 'total': total_num}, status=200)

    @action(detail=False, methods=['POST'])
    def studentQuery(self,request, *args, **kwargs):
        "获取班级所有人的姓名和id"
        clazz_id = request.data['clazz_id']
        name = request.data['name']
        sql = """
            select 
                au.id,
                au.name 
            from auth_user au
            inner join 
                tb_clazz tc on tc.id = au.clazz_id
            WHERE tc.id = %s 
            and au.name != %s 
            and au.is_staff= 0 
            and au.is_delete = 0
        """
        result = DBUtils.select_all(sql, (clazz_id,name,))

        return Response(data={'data': result}, status=200)

    @action(detail=False, methods=['POST'])
    def teacher_search(self,request):
        """获取任务信息，支持按名称搜索"""
        # 获取所有可能的搜索参数
        data = request.data
        print(data)
        title = request.data.get('title')
        user_id = request.data.get('user_id')
        print(title)
        # 如果没有任何搜索参数，返回400错误
        if not title and not user_id:
            return Response({"message": "请提供一个搜索参数"}, status=400)
        # 构建查询条件
        query = Q()
        query &= Q(title__icontains=title)

        # 执行查询，同时获取模块名和语言名的别名
        tasks = Task.objects.filter(query).annotate(
            m_name=F('module__name'),
            l_name=F('language__name')
        ).distinct()  # 添加distinct防止多对多关联导致的重复结果
        # 序列化结果
        serializer = self.get_serializer(tasks, many=True)
        # 返回结果
        return Response({
            "message": "查询成功",
            # "count": tasks.count(),
            "data": serializer.data
        })
    @action(detail=False, methods=['POST'])
    def assignTask(self, request, *args, **kwargs):
        """ 分配数据 """
        user_ids = request.data['userIds']
        task_id = request.data['task_id']
        sql = """
            insert into tb_task_user (is_solve, is_check, status, task_id, user_id)
            values (0, 0, 0, %s, %s)
        """
        for user_id in user_ids:
            DBUtils.insert(sql, args=(task_id, user_id,))
        return Response(data={'message': "分配成功"}, status=200)

    @action(detail=False, methods=['POST'])
    def deleteTask(self, request, *args, **kwargs):
        """ 删除任务 """
        user_ids = request.data['userIds']
        task_id = request.data['task_id']
        sql = """
                delete from tb_task_user where task_id = %s and user_id = %s
            """
        for user_id in user_ids:
            DBUtils.delete(sql, args=(task_id, user_id,))
        return Response(data={'message': "分配成功"}, status=200)

    @action(detail=False, methods=['POST'])
    def assignedUsers(self, request, *args, **kwargs):
        """ 查询分配后的任务的学生 """
        task_id = request.data['task_id']
        clazz_id = request.data['clazz_id']
        sql = """
        select 
            ttu.user_id as id
        FROM tb_task_user ttu
        INNER JOIN
            auth_user au on au.id =ttu.user_id
        inner join 
            tb_clazz tc on tc.id = au.clazz_id
        where au.clazz_id = %s and ttu.task_id = %s
        and au.is_staff = 0
        and au.is_delete = 0
        """
        data = DBUtils.select_all(sql, (clazz_id,task_id,))
        print(data)
        return Response(data={'data': data}, status=200)

    @action(detail=False, methods=['POST'])
    def answerAndUser(self, request, *args, **kwargs):
        """ 获取用户答案和任务 用来进行教师端的检查 """
        print(request.data)
        task_id = request.data['task_id']
        clazz_id = request.data['clazz_id']
        # print(task_id, clazz_id)
        sql = """
            select 
                au.id,
                au.name,
                ttu.answer 
            from tb_task_user ttu
            inner JOIN
                auth_user au on au.id = ttu.user_id
            inner join 
                tb_clazz tc on tc.id = au.clazz_id
            WHERE tc.id = %s 
            and ttu.task_id = %s
            and ttu.status = 3
            and au.is_staff = 0
        """

        data = DBUtils.select_all(sql, (clazz_id, task_id))

        return Response(data={'data': data}, status=200)

    @action(detail=False, methods=['GET'])
    def get_condition_list(self, request, *args, **kwargs):
        """获取所有的语言和模块 """
        condition_list = []

        sql = """
            SELECT 
              id AS lang_id, 
              name AS lang_name 
            FROM tb_language 
            WHERE is_delete = FALSE AND is_active = TRUE;
        """
        languages = DBUtils.select_all(sql)
        for lang_dict in languages:
            lang_id = lang_dict['lang_id']
            lang_name = lang_dict['lang_name']
            language_item = {
                "id": lang_id,
                "name": lang_name,
                "child": {
                    "name": "任务模块",
                    "value": "module",
                    "list": []
                }
            }
            sql2 = """
                SELECT 
                  id AS mod_id, 
                  name AS mod_name 
                FROM tb_module 
                WHERE language_id = %s AND is_delete = FALSE AND is_active = TRUE;
            """
            modules = DBUtils.select_all(sql2, (lang_id,))
            # 组装模块列表
            for mod_dic in modules:
                mod_id = mod_dic['mod_id']
                mod_name = mod_dic['mod_name']
                language_item["child"]["list"].append({
                    "id": mod_id,
                    "name": mod_name,
                })

            condition_list.append(language_item)

        return Response(data={'data': condition_list}, status=200)
    @action(detail=False, methods=['POST'])
    def checkStudentTask(self, request, *args, **kwargs):
        """检查任务名称"""
        print(request.data)
        user_id = request.data['studentId']
        task_id = request.data['taskId']

        print(user_id, task_id)

        sql = """
            update tb_task_user set status = 4 where task_id = %s and user_id = %s
        """

        DBUtils.update(sql, (task_id, user_id))

        return Response(status=200)

